package de.tum.in.eist.poll.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

import de.tum.in.eist.poll.shared.Lecture;
import com.google.gwt.user.client.ui.Label;

/**
 * Webpage on which the student can choose a lecture to give feedback on.
 * 
 * @author florian
 * 
 */
public class SelectLecture extends Webpage {
	private static SelectLectureUiBinder uiBinder = GWT
			.create(SelectLectureUiBinder.class);
	@UiField
	ListBox lectureList;
	@UiField
	Button select;
	@UiField Label noLectures;

	interface SelectLectureUiBinder extends UiBinder<Widget, SelectLecture> {
	}

	OnSelectLectureHandler onSelectLectureHandler;

	@Override
	public final void loadWebsite() {
		setContent(uiBinder.createAndBindUi(this));
		loadLectures();
	}

	/**
	 * Load the Website for Lectureselection.
	 */
	private void loadLectures() {
		// Set up the callback object.
		AsyncCallback<List<Lecture>> callback = new AsyncCallback<List<Lecture>>() {
			public void onFailure(final Throwable caught) {
				// TODO: Do something with errors.
			}

			public void onSuccess(final List<Lecture> result) {
				if (result != null) {
					// show lecture list
					for (Lecture lecture : result) {
						lectureList.addItem(lecture.getLectureTitle(),
								lecture.getLectureID());
					}
					select.addClickHandler(handler);
					select.setEnabled(true);

					if (result.size() == 1) {
						// if only one Lecture exists continue automatically
						select.click();
					} else if (result.size() == 0) {
						noLectures.setVisible(true);
					}
				} else {
					com.google.gwt.user.client.Window.alert("Not logged in");
				}
			}
		};

		getService().getOpenLectures(callback);
	}

	/**
	 * Clickhandler for the Select-Button.
	 */
	private ClickHandler handler = new ClickHandler() {

		@Override
		public void onClick(final ClickEvent event) {
			// select a lecture and go to the poll page
			if (onSelectLectureHandler != null
					&& lectureList.getSelectedIndex() != -1) {
				onSelectLectureHandler.selectLecture(lectureList
						.getValue(lectureList.getSelectedIndex()));
			}
		}

	};

	/**
	 * Set onSelectLectureHandler.
	 * 
	 * @param handler
	 *            Clickhandler for the Select-Button
	 */
	public final void setOnSelectLectureHandler(
			final OnSelectLectureHandler handler) {
		onSelectLectureHandler = handler;
	}
}
